package com.firebird.kotlin.mall.user.module.login

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import cn.pedant.SweetAlert.SweetAlertDialog
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.firebird.kotlin.mall.library.ext.enable
import com.kotlin.user.data.protocol.LoginResultResponse
import com.kotlin.user.injection.component.DaggerUserComponent
import com.kotlin.user.injection.module.UserModule
import com.firebird.kotlin.mall.library.ext.onClick
import com.firebird.kotlin.mall.library.mvp.view.activity.BaseMvpActivity
import com.firebird.kotlin.mall.library.util.AppPrefsUtils
import com.firebird.kotlin.mall.provider.PushProvider
import com.firebird.kotlin.mall.provider.common.ProviderConstant
import com.firebird.kotlin.mall.provider.router.RouterPath
import com.firebird.kotlin.mall.user.R
import com.firebird.kotlin.mall.user.module.forgetpwd.ForgetPwdActivity
import com.firebird.kotlin.mall.user.module.register.RegisterActivity
import com.firebird.kotlin.mall.user.util.UserPrefsUtils
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/*
  登录界面
 */
@Route(path = RouterPath.UserCenter.PATH_LOGIN)
class LoginActivity : BaseMvpActivity<LoginPresenter>(), LoginContract.View, View.OnClickListener {

    @Autowired(name = RouterPath.MessageCenter.PATH_MESSAGE_PUSH)
    @JvmField
    var mPushProvider: PushProvider? = null
    var dialog: SweetAlertDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPresenter.onAttach(this)
        setContentView(R.layout.activity_login)

        initView()
    }

    override fun performInject() {
        DaggerUserComponent.builder().activityComponent(mActivityComponent)
                .userModule(UserModule()).build().inject(this)
    }

    /*
      初始化视图
     */
    private fun initView() {
        mMobileEt.setText("demo")
        mPwdEt.setText("user123")
        mLoginBtn.enable(mMobileEt, { isBtnEnable() })
        mLoginBtn.enable(mPwdEt, { isBtnEnable() })
        mLoginBtn.onClick(this)
        mHeaderBar.getRightView().onClick(this)
        mForgetPwdTv.onClick(this)
    }

    /*
      点击事件
     */
    override fun onClick(v: View) {
        when (v?.id) {
            R.id.mLoginBtn ->{
                if (checkContent()){
                    dialog  =  SweetAlertDialog(this,SweetAlertDialog.PROGRESS_TYPE)
                           .setTitleText("正在登录...")
                    dialog?.setCancelable(false)
                    dialog?.show()
                }
                mPresenter.login(mMobileEt.text.toString(),mPwdEt.text.toString(), mPushProvider?.getPushId()
                        ?: "")
            }

            R.id.mRightTv -> {
                startActivity<RegisterActivity>()
            }


            R.id.mForgetPwdTv -> {
                startActivity<ForgetPwdActivity>()
            }
        }
    }

    /**
     * 判断
     */
    private fun checkContent():Boolean{
        mMobileEt.error=null
        mPwdEt.error=null

        var cancel=false
        var focusView:View?=null

        if(TextUtils.isEmpty(mMobileEt.text.toString())){
                mMobileEt.error="用户名不能为空"
                focusView=mMobileEt
                cancel=true
            }
        if(TextUtils.isEmpty(mPwdEt.text.toString())){
                mPwdEt.error== "密码不能为空"
                focusView=mPwdEt
                cancel=true
         }else if(mPwdEt.text.length<6){
                mPwdEt.error="密码长度不能小于6位"
                focusView=mPwdEt
                cancel=true
        }

        if(cancel){
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            if(focusView!=null){
                focusView.requestFocus()
            }
        }else{
            return true
        }
        return false
    }

    /*
     判断按钮是否可用
    */
    private fun isBtnEnable(): Boolean {
        return mMobileEt.text.isNullOrEmpty().not() &&
                mPwdEt.text.isNullOrEmpty().not()
    }

    /*
      登录回调
     */
    override fun onLoginResult(result: LoginResultResponse) {
        this.hideLoading()
        dialog?.changeAlertType(SweetAlertDialog.SUCCESS_TYPE)
        dialog?.titleText = result.errmsg
        //toast(result.errmsg)
        if(result.errno==0){
            AppPrefsUtils.instant.putString(ProviderConstant.KEY_SP_USER_NAME, mMobileEt.text.toString()?: "")
            AppPrefsUtils.instant.putString(ProviderConstant.KEY_SP_USER_MOBILE, mMobileEt.text.toString() ?: "")
            UserPrefsUtils.putUserInfo(result)
            finish()
        }
    }
    override fun onLoginError(message: String?) {
        this.hideLoading()
        dialog?.changeAlertType(SweetAlertDialog.ERROR_TYPE)
        dialog?.titleText = message
    }
}
